<template>
  <a-row :gutter="10">
    <a-col :span="leftTable">
      <div style="display: flex;justify-content: flex-end">
        <a-button type="primary" :loading="asyncLoading" @click="asyncRole">同步角色信息</a-button>
      </div>
      <common-search :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="search" @reset="reset"/>
<!--      <div style="margin-bottom: 10px">-->
<!--        <a-button type="primary" @click="handleAdd">-->
<!--          <template #icon>-->
<!--            <PlusOutlined />-->
<!--          </template>-->
<!--          新建角色-->
<!--        </a-button>-->
<!--        <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="apiBaseUrl+'/sys/role/importExcel'" @change="handleImportExcel">-->
<!--          <a-button style="margin-left: 5px" type="primary">-->
<!--            <template #icon>-->
<!--              <VerticalAlignTopOutlined />-->
<!--            </template>-->
<!--            导入-->
<!--          </a-button>-->
<!--        </a-upload>-->
<!--        <a-button style="margin-left: 5px" type="primary" @click="handleExport('角色管理')">-->
<!--          <template #icon>-->
<!--            <VerticalAlignBottomOutlined />-->
<!--          </template>-->
<!--          导出-->
<!--        </a-button>-->
<!--      </div>-->
      <my-alert :color="'info'" @onClearSelected="onClearSelected" :selectedRowKeys="selectedRowKeys"></my-alert>
      <common-table
          :columns="columns"
          :dataSource="dataList"
          v-model:localPagination="page"
          @paginationChange="onPageChange"
          :slots="['action']"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:'radio' }"
          v-model:loading="loading"
          :scroll="{ x: 'max-content'}"
          :rowKey="(record) => record.id"
      >
        <template #action="{ record }">
          <more-btn-container>
            <a @click="user(record)">用户</a>
            <a @click="authorize(record)">授权</a>
            <a @click="editRole(record)">编辑</a>
            <a-popconfirm
                title="是否要删除该角色?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
                @cancel="cancel"
            >
              <a>删除</a>
            </a-popconfirm>
          </more-btn-container>
        </template>
      </common-table>
    </a-col>
    <a-col :span="rightTable">
      <user-table @changeList="onSelectChange" v-if="showRight" ref="userTable" :id="id" :fatherDataList="userTableDataList" @close="closeRightTable"></user-table>
    </a-col>
  </a-row>
  <add-role-modal :openRole="openRole" @close="handleCloseAdd"></add-role-modal>
  <edit-role-modal v-if="openEditRole" :openRole="openEditRole" :items="items" @close="handleCloseEdit"></edit-role-modal>
  <role-permission-drawer :id="id" v-if="openRolePermissionDrawer" :openRolePermissionDrawer="openRolePermissionDrawer"
                          @close="closeRolePermission"/>
</template>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import CommonTable from "@/components/commonTable/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {computed, ref} from "vue";
import {addSyncRole, deleteRole, getUserRoleList} from "@/api/system/role.js";
import MoreBtnContainer from "@/components/moreBtnContainer/index.vue";
import MyAlert from "@/components/alert/my-alert.vue";
import AddRoleModal from "@/components/modal/addRoleModal.vue";
import {message, Modal} from "ant-design-vue";
import EditRoleModal from "@/components/modal/editRoleModal.vue";
import RolePermissionDrawer from "@/components/drawer/rolePermissionDrawer.vue";
import UserTable from "@/views/system/component/userTable.vue";
import useUserStore from "@/store/modules/user.js";
import {downFile} from "@utils/service/index.js";
import {getToken, removeToken} from "@utils/storage.js";
import router from "@/router/index.js";
import {apiBaseUrl} from "@utils/service/index.js";
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getUserRoleList,
  queryFactory: () => ({
    field:'id,,roleCode,roleName,createTime,action',
    order:'desc'
  })
})
const formItems = ref([
  {
    label: '角色名称',
    field: 'roleName',
    type: 'input'
  }
])
const columns = [
   {
     title: '角色编码',
     align: 'center',
     dataIndex: 'roleCode'
   },
   {
     title: '角色名称',
     align: 'center',
     dataIndex: 'roleName'
   },
   {
     title: '创建时间',
     dataIndex: 'createTime',
     align:"center",
     sorter: true,
   },
   {
     title: '操作',
     dataIndex: 'action',
     align: 'center',
   }
]
const selectedRowKeys = ref([])
const selectedRow = ref({})
const openRole = ref(false)
const openEditRole = ref(false)
const openRolePermissionDrawer = ref(false)
const items = ref({})
const id = ref()
const showRight = ref(false)
const asyncLoading = ref(false)
const userTable = ref()
const userTableDataList = ref([])
const userStore = useUserStore()
const leftTable = computed(() => {
  return showRight.value ? 12 : 24
})
const rightTable = computed(() => {
  return showRight.value ? 12 : 0
})
const tokenHeader = computed(() => {
  return { 'X-Access-Token': getToken() };
})
/**
 * 选中选项
 * @param e
 * @param v
 */
const onSelectChange = async (e,v) => {
  selectedRowKeys.value = e
  selectedRow.value = v
  id.value = v[0].id
  if(showRight.value){
    const res = await userTable.value.queryUserRoleList({
      field:'id,,username,realname,status_dictText,action',
      column:'create_time',
      order:'desc',
      roleId:id.value
    })
    userStore.useSon = false
    userTableDataList.value = res.result.records
  }else{
    showRight.value = true
  }
}
/**
 * 清空选中选项
 */
const onClearSelected = () => {
  selectedRowKeys.value = []
  showRight.value = false
}
const cancel = () => {

}
/**
 * 打开新增角色窗口
 */
const handleAdd = () => {
  openRole.value = true
}
/**
 * 关闭新增角色窗口
 */
const handleCloseAdd = () => {
  openRole.value = false
  reset()
}
/**
 * 打开编辑角色窗口
 * @param item
 */
const editRole = (item) => {
  openEditRole.value = true
  console.log(item)
  items.value = item
  console.log(items.value)
}
/**
 * 关闭编辑角色窗口
 */
const handleCloseEdit = () => {
  openEditRole.value = false
  reset()
}
/**
 * 删除角色
 * @param id
 */
const handleDelete = async (id) => {
  try{
    const res = await deleteRole('/sys/role/delete', { id: id })
      message.success(res.message);
      reset()
  }catch (e){
    message.error(e)
  }
}
/**
 * 打开角色权限窗口
 * @param item
 */
const authorize = (item) => {
  openRolePermissionDrawer.value = true
  id.value = item.id
}
/**
 * 关闭角色权限窗口
 */
const closeRolePermission = () => {
  openRolePermissionDrawer.value = false
}
/**
 * 打开用户窗口
 * @param item 选中的角色
 * @returns {Promise<void>}
 */
const user = async (item) => {
  id.value = item.id
  selectedRowKeys.value = [item.id]
  if(showRight.value){
    const res = await userTable.value.queryUserRoleList({
      field:'id,,username,realname,status_dictText,action',
      column:'create_time',
      order:'desc',
      roleId:id.value
    })
    userStore.useSon = false
    userTableDataList.value = res.result.records
  }else{
    showRight.value = true
  }
}
/**
 * 关闭右侧窗口
 */
const closeRightTable = () => {
  onClearSelected()
  showRight.value = false
}

/**
 * 同步角色
 */
const asyncRole = async () => {
  try{
    asyncLoading.value = true
    const res = await addSyncRole({})
    console.log(res)
    search()
    message.success('同步成功')
  }catch (e){
    message.error(e)
  }finally {
    asyncLoading.value = false
  }
}
</script>


<style scoped>

</style>
